package mars.mp3player.service;

import mars.mp3player.entity.Mp3Bean;
import mars.mp3player.utils.FileUtils;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.IBinder;
/**
 * mp3 
 * @author Administrator
 *
 */
public class PlayerService extends Service {
	private boolean isPlaying=false;
	private boolean isPause=false;
	private boolean isReleased=false;
	
	private MediaPlayer mediaPlayer=null;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Mp3Bean mp3Bean=(Mp3Bean) intent.getSerializableExtra("mp3Bean");
		int MSG=intent.getIntExtra("MSG", 0);
		if(MSG==AppConstant.PlayerMsg.PLAY_MSG){
			if(mp3Bean!=null){
				play(mp3Bean);
			}
		} else if(MSG==AppConstant.PlayerMsg.PAUSE_MSG){
			pause();
		} else if(MSG==AppConstant.PlayerMsg.STOP_MSG){
			stop();
		}
		return super.onStartCommand(intent, flags, startId);
	}
	/**
	 * 
	 */
	private void stop() {
		if(mediaPlayer!=null){
			if(isPlaying){
				if(!isReleased){
					mediaPlayer.stop();
					mediaPlayer.release();
					isReleased=true;
					isPlaying=false;
				}
			}
		}
	}

	/**
	 * 
	 */
	private void pause() {
		if(mediaPlayer!=null){
			if(isPlaying||isPause){
				if(!isPause){
					mediaPlayer.pause();
					isPause=true;
					isPlaying=false;
				}else{
					mediaPlayer.start();
					isPause=false;
					isPlaying=true;
				}
			}
		}
	}

	public void play(Mp3Bean mp3Bean){
		FileUtils fileUtils=new FileUtils();
		Uri uri=fileUtils.getFileUri("mp3",mp3Bean.getMp3Name());
		mediaPlayer=MediaPlayer.create(PlayerService.this, uri);
		if(!isPlaying){
			mediaPlayer.setLooping(false);
			mediaPlayer.start();
			if(mediaPlayer.isPlaying()){
				isPlaying=true;
				isReleased=false;
			}
		}
		
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {
				mp.stop();
				mp.release();
				isReleased=true;
				isPlaying=false;
			}
		});
	}

}
